<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * 描述:駕駛學校系統共用函數
 * 版本:V1.0
 * 作者:Abin
 */

//中文截取字符串 函數聲明
if (!function_exists('mb_substr')) {
  function mb_substr($str, $start, $len = '', $encoding="UTF-8"){
    return iconv_substr($str,$start,$len,$encoding);
  }
}

if (!function_exists('mb_strlen')) {
  function mb_strlen($str,$charset='UTF-8'){
    return iconv_strlen($str,$charset);
  }
}
//組合函數 截取
if(!function_exists('helper_strcut')){
  function helper_strcut($str,$length=60){
    $str_cut=mb_substr($str,0,$length,'utf-8');
    if(mb_strlen($str)>$length){
      $str_cut.='...';
    }
    return $str_cut;
  }
}


//如果php版本不支持json數據.
if (!function_exists('json_encode') && !function_exists('json_decode')) {
  require(APPPATH.'third_party/Json.php');
  function json_encode($str){
    return json::encode($str);
  }
  function json_decode($str){
    return json::decode($str);
  }
}

//判斷性別
if (!function_exists('convert_sex')){
  function convert_sex($sex=''){
    if(!empty($sex)){
      switch ($sex) {
        case 'M':
          return '男';
          break;
        case 'F':
          return '女';
          break;
        default:
          return 'Null';
          break;
      }
    }
  }
}

//发送手机短信,对联络电话进行筛选
if(!function_exists('filter_phone')){
  function filter_phone($telephone=''){
    if(!empty($telephone) && strlen($telephone)==8 && substr($telephone,0,1)=='6'){

    }
  }
}

//隨機生成密碼
if(!function_exists('helper_password')){
  function helper_password($length = 6,$array='chars'){
    // 密码字符集，可任意添加你需要的字符
    $chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
    'i', 'j', 'k','m', 'n', 'p', 'q', 'r', 's',
    't', 'u', 'v', 'w', 'x', 'y','z',
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
    $number=array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
    // 在 $chars 中随机取 $length 个数组元素键名
    $keys = array_rand($$array, $length);
    $password = '';
    for($i = 0; $i < $length; $i++){
        // 将 $length 个数组元素连接成字符串
        $rand=$$array;
        $password .= $rand[$keys[$i]];
    }
    return $password;  
  }
}

//發送手機短信.
if(!function_exists('helper_send_macau_sms')){
  //執行發送短信
  function helper_send_macau_sms($phone_number,$message_txt){
    if (!empty($phone_number) && !empty($message_txt)) {
      $url = 'http://smsmgr.three.com.mo/servlet/_xml';
      $phone_string='';
      if(is_array($phone_number) && count($phone_number)>0){
        foreach ($phone_number as $phone) {
          $phone_string.='<recipient>'.$phone.'</recipient>';
        }
      }else{
        $phone_string='<recipient>'.$phone_number.'</recipient>';
      }
      $data=<<<XML
        <?xml version="1.0" encoding="UTF-8"?>
        <!DOCTYPE jds SYSTEM "/home/httpd/html/dtd/jds2.dtd">
        <jds>
        <msg_send>
          {$phone_string}
          <content>{$message_txt}</content>
          <language>C</language>
        </msg_send>
        </account>
        </jds>
XML;
      $ch = curl_init();
      // set URL and other appropriate options
      curl_setopt($ch, CURLOPT_HEADER, 0);    
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);   
      curl_setopt($ch, CURLOPT_URL,$url);
      curl_setopt($ch, CURLOPT_POST, true);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
      // grab URL, and print
      $response = curl_exec($ch);
      $xml = simplexml_load_string($response);
      curl_close($ch);
      $send_result="發送成功";
      if(isset($xml->jerr))
        $send_result="發送失敗:".$xml->jerr;
      return $send_result;
    }
  }
}

//發送手機短信.
//中國大陸
/**状态:
  100 发送成功
  101 验证失败
  102 短信不足
  103 操作失败
  104 非法字符
  105 内容过多
  106 号码过多
  107 频率过快
  108 号码内容空
  109 账号冻结
  110 禁止频繁单条发送
  111 系统暂定发送
  112 有错误号码
  113 定时时间不对
  114 账号被锁，10分钟后登录
  115 连接失败
  116 禁止接口发送
  117 绑定IP不正确
  120 系统升级
**
**/
if(!function_exists('helper_send_china_sms')){
  function helper_send_china_sms($phone_number,$message_txt){
    if(!empty($phone_number) && !empty($message_txt)){
      $http = 'http://http.yunsms.cn/tx/';
      $data = array(
        'uid'=>'',          //用户账号
        'pwd'=>strtolower('aaa'), //MD5位32密码
        'mobile'=>$phone_number, //号码
        'content'=>$message_txt, //内容 如果对方是utf-8编码，则需转码iconv('gbk','utf-8',$content); 如果是gbk则无需转码
        'time'=>'',    //定时发送 $time=''
        'mid'=>'',     //子扩展号$mid=''
        'encode'=>'utf8',//設置為utf8格式
      );
      $re = post_china_SMS($http,$data);      //POST方式提交
      if(trim($re)=='100'){
        return "发送成功";
      }else{
        return "发送失败:状态：".$re;
      }
    }
  }

  //調用發送
  function post_china_SMS($url,$data=''){
    $row = parse_url($url);
    $host = $row['host'];
    $port = isset($row['port']) ? $row['port']:80;
    $file = $row['path'];
    $post='';
    while (list($k,$v) = each($data)){
      $post .= rawurlencode($k)."=".rawurlencode($v)."&"; //转URL标准码
    }
    $post = substr( $post , 0 , -1 );
    $len = strlen($post);
    $fp = @fsockopen( $host ,$port, $errno, $errstr, 10);
    if(!$fp){
      return "$errstr ($errno)\n";
    }else{
      $receive = '';
      $out = "POST $file HTTP/1.1\r\n";
      $out .= "Host: $host\r\n";
      $out .= "Content-type: application/x-www-form-urlencoded\r\n";
      $out .= "Connection: Close\r\n";
      $out .= "Content-Length: $len\r\n\r\n";
      $out .= $post;
      fwrite($fp, $out);
      while (!feof($fp)) {
        $receive .= fgets($fp, 128);
      }
      fclose($fp);
      $receive = explode("\r\n\r\n",$receive);
      unset($receive[0]);
      return implode("",$receive);
    }
  }
  function check_product_itemprice($product_id=0){
     $CI = & get_instance();
     if($product_id>0){
        $itemPrice = $CI->products_mdl->getItemPriceTotal($product_id);
        if($itemPrice) return true;
     }
     return false; 
  }
}
/*判断是否可以选项*/
function check_product_hasspec($product_id=0){
     $row = redCache("spec_items_".$product_id);
     if(!$row){
        return false;
     }
     return isset($row['specList']) && count($row['specList']) > 0 ? true : false;
}
function send_sms($content,$phone,$code="852"){
    //初始化
    $ch = curl_init();
    //设置选项，包括URL
    curl_setopt($ch, CURLOPT_URL, "http://api.accessyou.com/sms/sendsms-utf8.php?msg=".$content."&phone=".$code.$phone."&pwd=76134381&accountno=11031590");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    //执行并获取HTML文档内容
    $output = curl_exec($ch);
    //释放curl句柄
    curl_close($ch);
    //打印获得的数据
    if(preg_match("/^[0-9]{9}$/", $output)){
       return $output;
    }
    return $output;
}

function format_content_tags($content=null){
  $content = preg_replace("/\[img\](.*?)\[\/img\]/is", "<img src='$1' width='100%'/>", $content);
  $content = preg_replace("/\[url=(.*?)\](.*?)\[\/url\]/is", "<a href='$1' title='$2'>$2</a>", $content);
  $content = preg_replace("/\[color=(.*?)\](.*?)\[\/color\]/is", "<font color='$1'>$2</font>", $content);
  $content = preg_replace("/\[u\](.*?)\[\/u\]/is", "<u>$1</u>", $content);
  $content = preg_replace("/\[b\](.*?)\[\/b\]/is", "<b>$1</b>", $content);
  $content = preg_replace("/\[i\](.*?)\[\/i\]/is", "<i>$1</i>", $content);
    $content = preg_replace("/\\n/is", "<br />", $content);
  return $content;
}
/*把数组中的id最短的额值作为数组的键*/
function key_format_value($arr){
  $base = array();
  if(is_array($arr)){
      foreach ($arr as $key => $value) {
        $base[$value['id']] = $value;
      }
  }
  return $base;
}

/**
* 数字转字母 （类似于Excel列标）
* @param Int $index 索引值
* @param Int $start 字母起始值
* @return String 返回字母
* @author Anyon Zou <Anyon@139.com>
* @date 2013-08-15 20:18
*/
function mchr($index, $start = 65) {
  $str = '';
  if (floor($index / 26) > 0) {
      $str .= mchr(floor($index / 26)-1);
  }
  return $str . chr($index % 26 + $start);
}
function writhCache($data=array(),$file_name=null){
    $file =  dirname(BASEPATH)."/".APPPATH."cache/specs/".$file_name.".php";
    if(!is_dir(dirname($file))){
        mk_dir(dirname($file));
    }
    file_put_contents($file, "<?php return ".var_export($data, true).";");
}
function redCache($file_name){
  $file =  dirname(BASEPATH)."/".APPPATH."cache/specs/".$file_name.".php";
  if(file_exists($file)){
       return include($file);
  }
  return null;
}
/*格式化费用*/
function format_free($total=0,$num=2){
  return sprintf("%.".$num."f", (double)$total);
}
/*排序数据*/
function sort_spec($a, $b){
   if($a['sort'] == $b['sort']){
      return 0;
   }
   return ($a['sort'] < $b['sort']) ? -1 : 1;
}
function curl_get($path1,$path2,$demo="http://demo.hoklee.com/"){
//    $ch = curl_init();
//    $timeout = 30;
//    curl_setopt ($ch, CURLOPT_URL, $demo.$path);
//    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
//    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
//    $file_contents = curl_exec($ch);
//    curl_close($ch);
//    return $file_contents;

    // 创建一对cURL资源
    $ch1 = curl_init();
    $ch2 = curl_init();
    $timeout = 1;
    file_put_contents('123.txt',$path1.$path2);
// 设置URL和相应的选项
    curl_setopt($ch1, CURLOPT_URL, $demo.$path1);
    curl_setopt($ch1, CURLOPT_HEADER, 0);
    curl_setopt ($ch1, CURLOPT_CONNECTTIMEOUT, $timeout);
    curl_setopt($ch2, CURLOPT_URL, $demo.$path2);
    curl_setopt($ch2, CURLOPT_HEADER, 0);
    curl_setopt ($ch2, CURLOPT_CONNECTTIMEOUT, $timeout);
// 创建批处理cURL句柄
    $mh = curl_multi_init();

// 增加2个句柄
    curl_multi_add_handle($mh,$ch1);
    curl_multi_add_handle($mh,$ch2);

    $running=null;
// 执行批处理句柄
    do {
        usleep(10000);
        $curl_multi_exec  = curl_multi_exec($mh,$running);
    } while ($running > 0);
// 关闭全部句柄
    curl_multi_remove_handle($mh, $ch1);
    curl_multi_remove_handle($mh, $ch2);
    curl_multi_close($mh);
    return $curl_multi_exec;
}